﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ZhongJia.Web.Framework;
using GuanQL.Service.Accounts.Dto;
using GuanQL.Service.Medias;
using GuanQL.Core.Domain.Accounts;
using ZhongJia.Community.Service.Accounts;
using GuanQL.Service.Accounts;
using GuanQL.Core;
using GanQL.Web.Infrastructure;
using Microsoft.Extensions.Options;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using ZhongJia.Core.Utility;

namespace GanQL.Web.Controllers
{
    [Route("api/[controller]")]
    public class AccountController : BaseController
    {

        private readonly PictureService _pictureService;
        private readonly GQLUserManager<User> _userManager;
        private readonly TokenProviderOptions _options;
        private readonly IWebContext _webContext;
        private readonly AccountService _accountService;
     

        /// <summary>
        /// Account
        /// </summary>
        /// <param name="userManager"></param>
        /// <param name="pictureService"></param>
        /// <param name="options"></param>
        /// <param name="webContext"></param>
        /// <param name="accountService"></param>
        /// <param name="appService"></param>
        public AccountController(
                GQLUserManager<User> userManager,
                PictureService pictureService,
                IOptions<TokenProviderOptions> options,
                IWebContext webContext,
                AccountService accountService)
        {
            _options = options.Value;
            _userManager = userManager;
            _pictureService = pictureService;
            _webContext = webContext;
            _accountService = accountService;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody]RegisterInput request)
        {
            if (!ModelState.IsValid)
                return ErrorToJson();

            var user = await _userManager.Login(request.Mobile, request.VerificationCode);
            return Json(true, data: new
            {
                Id = user.Id,
                access_token = GetToken(user),
                name = user.GetDisplayName(),
                mobile = user.PhoneNumber,
                avatarId = user.AvatarId,
                avatarUrl = await _pictureService.GetPictureUrl(user.AvatarId),
                expires_in = (int)_options.Expiration.TotalSeconds,
            });
        }
        /// <summary>
        /// GetToken
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string GetToken(User user)
        {
            var now = SystemClock.Now;
            var claims = new Claim[]
                {
                            new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim(JwtRegisteredClaimNames.Iat,  DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                            new Claim(ClaimTypes.Name, user.UserName),
                            new Claim(ClaimTypes.Role, GlobleConsts.Role.Register),
                            new Claim(ClaimTypes.UserData, user.TenantId.ToString())
                };

            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials
            );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return encodedJwt;
        }
    }
}
